package sample3.provider.ddl;

import java.util.ArrayList;
import java.util.List;

import sample3.provider.dml.SqliteWhereBuilder;

public class SqliteTriggerBuilder extends AbsDdlBuilder {
    private String mTargetTable;
    private String mAction;
    private List<String> mWorkList = new ArrayList<String>();

    SqliteTriggerBuilder(String name) {
        super(name + "_trigger");
    }

    public SqliteTriggerBuilder setDeleteOnTable(String targetTable) {
        mAction = " UPDATE ";
        mTargetTable = targetTable;
        return this;
    }
    public SqliteTriggerBuilder setInsertOnTable(String targetTable) {
        mAction = " INSERT ";
        mTargetTable = targetTable;
        return this;
    }
    public SqliteTriggerBuilder setUpdateOnTable(String targetTable) {
        mAction = " UPDATE ";
        mTargetTable = targetTable;
        return this;
    }
    public SqliteTriggerBuilder addUpdateWork(String updateTable, String set, String where) {
        mWorkList.add(" UPDATE " + updateTable + " SET " + set + " WHERE " + where);
        return this;
    }
    public SqliteTriggerBuilder addDeleteWork(String deleteTable, SqliteWhereBuilder where) {
        mWorkList.add(" DELETE " + deleteTable + " WHERE " + where);
        return this;
    }
    public SqliteTriggerBuilder addInsertWork(String insertTable, String key, String value) {
        mWorkList.add(" INSERT " + insertTable + " INTO " + key + " VALUES " + value);
        return this;
    }

    @Override
    String toCreateSql() {
        StringBuilder sql = new StringBuilder();
        // begin
        sql.append("CREATE TRIGGER IF NOT EXISTS ").append(getName()).append(mAction).append(" ON ").append(mTargetTable);
        sql.append(" BEGIN ");
        // do
        boolean addComma = false;
        for (String work : mWorkList) {
            if (addComma) {
                sql.append(',');
            }
            addComma = true;
            sql.append('\n').append(work).append(";");
        }
        // end
        sql.append(" END ");
        return sql.toString();
    }
    @Override
    String toDropSql() {
        return "DROP TRIGGER IF EXISTS " + getName();
    }

}
